// pages/cart/cart.js
Page({
  data:{
    isManageMode: false,   // 管理模式状态
    cartList: [],          // 购物车数据
    selectedCount: 0,      // 已选数量
    totalAmount: 0,        // 总金额
    isAllChecked: false,    // 全选状态
    isCartEmpty: true,   // 空状态

    statusBarHeight: getApp().globalData.statusBarHeight, // 状态栏高度
    navHeight: getApp().globalData.navHeight,       // 导航栏总高度
    tabBarHeight: getApp().globalData.tabBarHeight,  // 底部高度
  },

  onShow() {
    this.loadCartData();
  },

  // 加载购物车数据
  loadCartData() {
    const cartList = wx.getStorageSync('cart') || [];
    this.setData({ 
      cartList,
      isCartEmpty: cartList.length === 0
     }, this.calculateTotal);
  },

  // 切换管理模式
  toggleManageMode() {
    this.setData({
      isManageMode: !this.data.isManageMode,
      isAllChecked: false
    }, this.clearSelection);
  },

  // 切换单个商品选中状态
  toggleCheck(e) {
    const index = e.currentTarget.dataset.index;
    const cartList = this.data.cartList.map((item, i) => {
      if (i === index) item.checked = !item.checked;
      return item;
    });
    this.updateCartData(cartList);
  },

  // 全选/反选
  toggleAllCheck() {
    const isAllChecked = !this.data.isAllChecked;
    const cartList = this.data.cartList.map(item => ({
      ...item,
      checked: isAllChecked
    }));
    this.updateCartData(cartList);
  },

  // 删除选中商品
  deleteSelected() {
    wx.showModal({
      title: '提示',
      content: '确定删除选中商品？',
      success: res => {
        if (res.confirm) {
          const cartList = this.data.cartList.filter(item => !item.checked);
          this.updateCartData(cartList);
          this.toggleManageMode();
        }
      }
    });
  },

  // 数量修改
  changeQuantity(e) {
    const { index, type } = e.currentTarget.dataset;
    const cartList = [...this.data.cartList];
    const current = cartList[index];
    let maxStock = current.stock ? current.stock : 0
    if (type === 'minus' && current.count <= 1) return;
    current.count += type === 'plus' ? 1 : -1;
    if(current.count > maxStock){ 
      current.count = maxStock
      wx.showToast({ title: `不能超过库存${maxStock}`, icon: 'none' });
    }

    this.updateCartData(cartList);
  },

  // 输入框修改数量
  inputQuantity(e) {
    const { index } = e.currentTarget.dataset;
    const value = parseInt(e.detail.value) || 1;
    const cartList = [...this.data.cartList];
    const current = cartList[index];
    current.count = Math.max(1, value);
    let maxStock = current.stock ? current.stock : 0
    if(current.count > maxStock){ 
      current.count = maxStock
      wx.showToast({ title: `不能超过库存${maxStock}`, icon: 'none' });
    }else if (current.count < 1) {
      current.count = 1;
      wx.showToast({ title: '数量不能小于1', icon: 'none' });
    }
 
    this.updateCartData(cartList);
  },

  // 更新数据并计算
  updateCartData(cartList) {
    wx.setStorageSync('cart', cartList);
    this.setData({ cartList }, this.calculateTotal);
  },

  // 计算总金额和选中数量
  calculateTotal() {
    let total = 0;
    let count = 0;
    let allChecked = true;
    let allCount = 0;
    this.data.cartList.forEach(item => {
      allCount += item.count
      if (item.checked) {
        total += Number(item.price) * Number(item.count);
        count++;
      }
      if (!item.checked) allChecked = false;
    });
    
    this.setData({
      totalAmount: total.toFixed(2),
      selectedCount: count,
      isAllChecked: allChecked
    });

    const app = getApp()
    app.globalData.cartCount = allCount  //更新全局角标数
    app.updateTabBarBadge() // 直接调用全局更新方法(购物车角标)
  },

  // 清空选中状态
  clearSelection() {
    const cartList = this.data.cartList.map(item => ({
      ...item,
      checked: false
    }));
    this.updateCartData(cartList);
  },

  // 返回上一页
  navigateBack(delta = 1) {
    const pages = getCurrentPages()
    if (pages.length > delta) {
      wx.navigateBack({ delta })
    } else {
      wx.reLaunch({ url: '/pages/index/index' })
    }
  },


  // 跳转结算
  GoOrders() {
    if (this.data.selectedCount === 0) {
      wx.showToast({ title: '请选择商品', icon: 'none' });
      return;
    }
    // wx.navigateTo({ url: '/pages/orders/orders' });
    // const eventChannel = this.getOpenerEventChannel();
    wx.navigateTo({
      url: '/pages/orders/orders',
      success: (res) => {
        res.eventChannel.emit('sendOrderData', {
           goodsType: 'cart',  // : 'buyNow',
          // selectedItems: wx.getStorageSync(fromCart ? 'cart' : 'buyNow')
          selectedItems: this.data.cartList
        })
      }
    })
  }
});
